package com.game.server;

import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.game.share.IOPackage;
import com.game.share.StreamReader;
import com.game.share.StreamWriter;

public class SocketThread implements Runnable {
	private final Socket socket;

	boolean isClose;

	SocketThread(Socket socket) {
		this.socket = socket;
		isClose = false;
	}

	public void close() {
		isClose = true;
	}

	public void run() {
		try {
			InputStream input = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			// init
			StreamReader reader = new StreamReader(input);
			StreamWriter writer = new StreamWriter(out);

			// read --> process --> write
			while (!isClose) {
				IOPackage pkg = null;
				try {
					pkg = reader.readPackage();
				} catch (EOFException e) {
					// @ TODO disconnection
					return;
				}
				if (pkg != null) {
					System.out.println("receive package");
					IOPackage result = processPackage(pkg);
					writer.writePackage(result);
					writer.flush();
				}
				writer.flush();
			}
			out.close();
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("close socket");
		}
	}

	int count = 0;

	private IOPackage processPackage(IOPackage pkg) {
		StreamReader reader = new StreamReader(new ByteArrayInputStream(
				pkg.getData()));
		String actionName = null;
		String jsonString = null;
		try {
			actionName = reader.readString();
			jsonString = reader.readString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (actionName != null) {
			Action action = NetworkService.get().getAction(actionName);
			if (action != null) {
				IOPackage output = action.execute(this, jsonString);
				System.out.println("send back : " + actionName);
				return output;
			}
		}
		return IOPackage.EMPRY_RESPONSE;
	}

}
